// 描述电影列表的类型状态

import type { Reducer } from "react";
import type { ISearchCondition } from "../../services/CommonTypes";
import type { IMovie } from "../../services/MovieService";
import type { DeleteAction, saveMovieAction, SetConditionAction, SetLoadingAction } from "../actions/MovieActions";

export type IMovieCondition = Required<ISearchCondition>

export interface IMovieState {
    data: IMovie[],
    condition: IMovieCondition,
    total: number,
    isLoading: boolean,
}

const defaultState: IMovieState = {
    data: [],
    condition: {
        page: 1,
        limit: 10,
        key: ""
    },
    total: 0,
    isLoading: false
}

type MovieReducer<A> = Reducer<IMovieState, A>

const setCondition: MovieReducer<SetConditionAction> = function (state, action) {
    return {
        ...state,
        condition: {
            ...state.condition,
            ...action.payload,
        }
    }
}

const saveMovie: MovieReducer<saveMovieAction> = function (state, action) {
    return {
        ...state,
        data: action.payload.movies,
        total: action.payload.total,
    }
}
const setLoading: MovieReducer<SetLoadingAction> = function (state, action) {
    return {
        ...state,
        isLoading: action.payload,
    }
}

const deleteMovie: MovieReducer<DeleteAction> = function (state, action) {
    return {
        ...state,
        data: state.data.filter(movie => movie._id !== action.payload),
        total: state.total - 1,
    }
}



export type MovieActions = saveMovieAction | SetLoadingAction | SetConditionAction | DeleteAction

export default function (state: IMovieState = defaultState, action: MovieActions) {
    switch (action.type) {
        case 'movie_delete':
            return deleteMovie(state, action)
        case 'movie_save':
            return saveMovie(state, action)
        case 'movie_setCondition':
            return setCondition(state, action)
        case 'movie_setLoading':
            return setLoading(state, action)
        default:
            return state
    }
}